package com.demo.function.dataauth.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.demo.function.dataauth.interceptor.DataAuthInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

/**
 * 配置mybatis拦截器
 */
@Configuration
public class DataAuthInterceptorConfig implements InitializingBean {

    @Resource
    private List<SqlSessionFactory> sqlSessionFactoryList;

    /**
     * 控制拦截器执行顺序
     * @throws Exception 异常
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            // mybatis plus分页插件
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

            // 设置插件顺序，执行顺序是从下往上
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            configuration.addInterceptor(interceptor);
            configuration.addInterceptor(new DataAuthInterceptor());
        }
    }
}
